// pages/vant/vant.js
Page({
  data: {
    lists:[]
  },
  onLoad: function (options) {
      var lists = wx.getStorageSync('lists')
      // 有缓存，则加载缓存，没有缓存设置缓存
      if(lists){
        this.setData({
          lists
        })
      }else{
        wx.setStorageSync('lists', [])
      }
  },
  onSearch(event){
    // 添加的时候看缓存中是否有对应的的item
    var value = event.detail
    var lists = wx.getStorageSync("lists")
    var res = lists.every(item=>item.name!=value)  // 去重
    if(res && value.trim()){
      lists.push({
        name:value,
        state:false
      })
      wx.setStorageSync("lists",lists)
      this.setData({
        lists
      })
    }else{
      wx.showToast({
        title: '数据已经存在',
        icon: 'error'
      })
    }
  },
  onChange(event){
    var value = event.detail
    var lists = wx.getStorageSync("lists")
    var obj = lists[event.currentTarget.dataset.index]
    obj.state = value
    wx.setStorageSync('lists', lists)
    this.setData({
      lists
    })
  },
  onDelete(event){
    var name = event.currentTarget.dataset.name
    var lists = wx.getStorageSync('lists')
    var res = lists.filter(item=>item.name!=name)
    wx.setStorageSync('lists', res)
    this.setData({
      lists:res
    })
  }
})